package org.vectrics.recruiter.html;

import java.util.Collection;
import java.util.Iterator;

import org.vectrics.SystemException;
import org.vectrics.common.util.FileUtil;
import org.vectrics.domain.Domain;
import org.vectrics.domain.HtmlCssEntry;
import org.vectrics.domain.HtmlFormType;
import org.vectrics.hibernate.ThreadProperties;
import org.vectrics.provider.CoreServiceLocator;

public abstract class ThemeBuilder {
	private Collection cssEntries = null;
	private Domain domain = null;
	private HtmlFormType formType = null;

	public ThemeBuilder(Domain domain, HtmlFormType formType) {
		super();
		this.cssEntries = CoreServiceLocator.getSystemService().findCssEntries(domain, formType);
		this.domain = domain;
		this.formType = formType;
	}
	
	protected abstract void setEntryValues();
	
	public void execute() {
		setEntryValues();
		ThreadProperties.forcedCommit();
		removeCachedFile();
	}
	
	private void removeCachedFile() {
		String fileName = this.formType.getCssFileName(this.domain);
		FileUtil.deleteFileIfExists(fileName);
	}
	
	protected void setEntry(String className, String property, String value) {
		HtmlCssEntry entry = this.findEntry(className, property);
		if (entry != null) {
			entry.setValue(value);
			ThreadProperties.getSession().update(entry);
		} else {
			throw new SystemException("HtmlCssEntry not found for class: " + className 
					+ "  Property: " + property + "  Domain=" + this.domain);
		}
	}
	
	protected HtmlCssEntry findEntry(String className, String property) {
		HtmlCssEntry found = null;
		
		Iterator iter = this.cssEntries.iterator();
		while ((found == null) && (iter.hasNext())) {
			HtmlCssEntry entry = (HtmlCssEntry)iter.next();
			if ((entry.getClassName().toLowerCase().equals(className.toLowerCase())) && (entry.getParameter().toLowerCase().equals(property.toLowerCase()))) {
				found = entry;
			}
		}
		return(found);
	}

}
